import request from '@/utils/request'
import { removeTokenInfo, setTokenInfo } from '@/utils/storage'
import { Dispatch } from 'redux'

export const senCode = (mobile: string) => {
  return async () => {
    await request({
      url: `sms/codes/${mobile}`,
      method: 'GET',
    })
  }
}
/**
 * 保存token
 */
type Token = {
  token: string
  refresh_token: string
}
export const saveToken = (payload: Token) => {
  return {
    type: 'login/token' as const,
    payload,
  }
}
/**
 * 登录功能
 */
export const login = (data: { mobile: string; code: string }) => {
  return async (dispatch: Dispatch) => {
    const res = await request({
      method: 'POST',
      url: '/authorizations',
      data,
    })
    // console.log(res);
    // 把token存储到redux中
    dispatch(saveToken(res.data))
    // 把token存储在本地
    setTokenInfo(res.data)
  }
}

export const logout = () => {
  return (dispatch: Dispatch) => {
    // 删除本地token
    removeTokenInfo()
    // 删除redux中的token
    dispatch({
      type: 'login/logout',
    })
  }
}
